package com.wcity.manage.common.utils;

import jxl.Workbook;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;
import jxl.write.biff.RowsExceededException;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * Created by zm on 2016/12/21.
 */
public class ExcelUtil {
    /**
     * list为MAP()类型数据
     * @param fileName 文件名
     * @param title 标题
     * @param list 数据对象
     * @throws throws IOException, WriteException
     * @throws IOException
     * @throws WriteException
     * @throws RowsExceededException
     */
    public static void exportDataForMap(HttpServletResponse response, String fileName,String[] title, List<Map<String, Object>> list)throws IOException, WriteException{
        if(list.size()==0 || list==null){
            return;
        }
        WritableWorkbook wwb = null;
        int num = 0;

        //创建xls表格
        response.setContentType("application/vnd.ms-excel");
        response.setHeader("Content-Disposition", "attachment; filename=\""+ new String((fileName+".xls").getBytes("gb18030"), "iso8859-1") + "\"");
        wwb = Workbook.createWorkbook(response.getOutputStream());
        WritableSheet ws = wwb.createSheet("sheet1", 0);
        for (int i = 0; i < title.length; i++) {
            jxl.write.Label lab = new jxl.write.Label(i, 0, title[i]);
            ws.addCell(lab);
        }
        for(int i=0;i<list.size();i++){
            Map<String,Object> map = list.get(i);
            Set<Map.Entry<String, Object>> set = map.entrySet();
            for(Map.Entry<String, Object> entry:set){
                jxl.write.Label lab = new jxl.write.Label(num, i+1, entry.getKey()!=null? entry.getValue().toString():"");
                num++;
                ws.addCell(lab);
                if(num==set.size()) num=0;
            }
        }
        wwb.write();
        wwb.close();

    }
}
